package handlers

import (
	"fmt"
	"log"
	"luntan/pkg/models"
	"net/http"

	"github.com/gorilla/websocket"
)

var Connections = make(map[string]*(models.User))

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		// 允许特定的 Origin
		allowedOrigin := "http://localhost:8080"
		return r.Header.Get("Origin") == allowedOrigin
	},
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func Msg(w http.ResponseWriter, req *http.Request) {
	session, _ := Session_store.Get(req, "session-luntan")
	sid, _ := session.Values["sid"].(string)
	if sid == "" {
		fmt.Fprintf(w, `{"status":-1,"msg":"%s"}`, "sid is empty")
		return
	}
	// upgrade to ws
	conn, err := upgrader.Upgrade(w, req, nil)
	if err != nil {
		log.Println(err)
		fmt.Fprintf(w, `{"status":-1,"msg":"%s"}`, err.Error())
		return
	}

	name, _ := session.Values["name"].(string)
	Connections[sid] = &models.User{Account: name, Conn: conn}

	go func() {
		defer conn.Close()
		fmt.Println("ws out")
		for {
			// get msg
			messageType, p, err := conn.ReadMessage()
			if err != nil {
				log.Println(err)
				delete(Connections, sid)
				return
			}
			// broadcast
			broadcast(messageType, p, sid)
		}
	}()
}
func broadcast(msgType int, p []byte, sid string) {
	for k, v := range Connections {
		/*
			if k == sid {
				continue
			}
		*/
		var name = Connections[sid].Account
		msg := fmt.Sprintf(`{"name":"%s","msg":"%s", "self": %t }`, name, p, k == sid)
		msg_byte := []byte(msg)
		if err := v.Conn.WriteMessage(msgType, msg_byte); err != nil {
			delete(Connections, k)
			log.Println(err)
			return
		}
	}
	fmt.Printf("conns: %d\n", len(Connections))
}
